import XLSX from 'xlsx';
import {getStrCharLen} from "@/utils/service";

/**
 * 生成标题
 * */
export function builderTitle(tableData) {
    //返回值
    let r = ""
    //使用到的关键词
    let useKey = []
    tableData.forEach(item => {
        let t = item.name.replace(/\s/g, "")
        console.log(t);
        if (getStrCharLen(r + t) > 60) {
            return
        }
        let index = false
        for (const element of useKey) {
            // 当前词中的字符串已经被完全使用
            if (element.includes(t)) {
                index = true
                break;
            // 当前词中部分字符串已被使用
            }else if(t.includes(element)){
                t = t.replace(element,"")
            }
        }
        // 当前词没有被使用过
        if (!r.includes(t) && !index) {
            r += t
            useKey.push(t)
        }
    })
    return r
}

/**
 * 根据表格数据,构造补单计划
 * */
export function builderOrderPlan(vue, tableData, days = 30) {
    // 总补单数量
    let sumCount = 0;
    let list = tableData.map(item => {
        let count = item.searchPeopleNum / 10000
        if (count >= 1) {
            count = Math.floor(count)
        } else {
            count = Math.ceil(count)
        }
        sumCount += count
        let r = {name: item.name, count: count}
        for (let i = 1; i <= days; i++) {
            r["day" + i] = 0
        }
        return r
    })
    // 每天补单最大数量
    let dayMaxCount = Math.ceil(sumCount / days)
    // 计算补单
    list.forEach((item, index) => {
        // 每天补单数
        let avg_num = Math.floor(item.count / days)
        avg_num = avg_num > 1 ? avg_num : 1
        allotOrderV2(list, index, dayMaxCount, avg_num, item.count, 1, days)
    })
    list.forEach((item, index) => {
        for (let i = 1; i <= days; i++) {
            item["day" + i] = item["day" + i] === 0 ? "" : item["day" + i]
        }
    })
    convertExcelDW(vue, list, days)
}

/**
 * 补单 excel 下载
 * */
function convertExcelDW(vue, list, days) {
    list = list.map(item => Object.values(item))
    let title = ["关键词", "补单数"]
    for (let i = 1; i <= days; i++) {
        title.push("第" + i + "天")
    }
    list.unshift(title);
    // 创建工作簿对象
    const workbook = XLSX.utils.book_new();

    // 创建工作表对象
    const worksheet = XLSX.utils.aoa_to_sheet(list);

    // 将工作表对象添加到工作簿对象中
    XLSX.utils.book_append_sheet(workbook, worksheet, "Sheet1");

    // 将工作簿对象转换为二进制数据流
    const excelBuffer = XLSX.write(workbook, {bookType: "xlsx", type: "array"});
    vue.$download.excel(excelBuffer, "补单周期.xlsx")
}

/**
 * 将订单分配到指定天数内，使得每天订单数量尽量平均
 * @param {Array} data - 数据列表
 * @param {number} index - 指定关键词在数据列表的下标
 * @param {number} dayMaxCount - 每天最大订单数量
 * @param {number} num - 当前天补单数量
 * @param {number} avg_num - 每天平均分配量
 * @param {number} day - 当前分配的天索引
 * @param {number} days - 需要分配的天数
 * @returns
 */
function allotOrderV2(data, index, dayMaxCount, avg_num, num, day, days) {
    // 递归结束
    if (num <= 0) {
        return
    }
    if (day > days) {
        // 如果还有存余 则分配余单
        avg_num = Math.floor(num / days)
        avg_num = avg_num > 1 ? avg_num : 1
        allotOrderV2(data, index, dayMaxCount, avg_num, num, 1, days)
        return
    }
    // 获取当前天还能分配的订单数量
    let count = dayMaxCount - countDayNum(data, day)
    if (count > 0) {
        // 获取即将分配的订单数量
        let useNum = avg_num !== 0 && num >= avg_num ? avg_num : num
        // 不足以全部分配则分配可接受量
        useNum = useNum >= count ? count : useNum
        data[index]["day" + day] += useNum
        // 计算剩余分配的数量
        num -= useNum
    }
    day += 1
    allotOrderV2(data, index, dayMaxCount, avg_num, num, day, days)
}

/**
 * 统计数据中指定天索引的补单数量
 * @param {Array} data - 数据列表
 * @param {number} day - 指定天数
 * */
function countDayNum(data, day) {
    let r = 0
    data.forEach(item => r += item["day" + day])
    return r
}

/**
 * 发布任务请求
 * */
export function pushTask(vue, params) {
    const loading = vue.$loading({
        lock: true, text: '发布中', spinner: 'el-icon-loading', background: 'rgba(0, 0, 0, 0.7)'
    });
    vue.$request.post({
        url: "operationAid/task/updateTitleOrZtcAddKeyWord", params: params, success: res => {
            console.log(res)
            vue.$message.success("发布任务成功")
        }, allError: err => {
            console.log(err)
        }, finally: res => {
            loading.close();
        }
    })
}

/**
 * 提交关键词的用途记录
 * */
export function commitUsageRecord(vue, row) {
    vue.$request.post({
        url: "operationAid/KeyWordUsageRecord/commit", params: {
            ...row
        }, success: res => {
            vue.$notify({
                message: '提交用途记录成功', type: 'success', duration: 2000
            });
        }, error: err => {
            console.log(err)
        }, finally: res => {
        }
    })
}

export function batchCommitUsageRecord(vue, selectRow, markSwitch, isAppendZtc, isGenerateTitle, isGenerateOrderPlan,groupId) {
    vue.$request.post({
        url: "operationAid/KeyWordUsageRecord/markV2", params: {
            keyWordJsonList: JSON.stringify(selectRow.map(item => {
                return {
                    ...item
                }
            })),
            categoryName: selectRow[0].categoryName,
            markSwitch: markSwitch,
            isAppendZtc: isAppendZtc,
            isGenerateTitle: isGenerateTitle,
            isGenerateOrderPlan: isGenerateOrderPlan,
            groupId: groupId === 0 ? undefined : groupId
        }, success: res => {
            vue.$notify({
                message: '提交成功', type: 'success', duration: 2000
            });
            vue.getTableData()
        }, error: err => {
            console.log(err)
        }, finally: res => {
        }
    })
}

/**
 * 获取类目选项
 * @param targetField 字段
 * @param vue 当前页面对象 即 this
 * @param finallyFunc 结束函数
 * */
export function getCategoryOptions(vue,targetField, finallyFunc = r => {}){
    vue.$request.post({
        url: "operationAid/KeyWord/categoryNameList",
        success: res => {
             vue[targetField] = res
        },
        error: err => {
            console.log(err)
        },
        finally: finallyFunc
    })
}

/**
 * 根据品类和标记 获取关键词用途数据列表记录
 * @param categoryName {string} 品类名称
 * @param mark {string} 标记类型 IS_APPEND_ZTC/IS_GENERATE_TITLE/IS_GENERATE_ORDER_PLAN
 * @param success {Function} 请求成功的回调方法
 * @param vue {Vue} 当前页面对象 即 this
 * @param groupId
 * */
export function keyWordUsageRecordList(vue,categoryName,groupId,mark,success){
    vue.$request.post({
        url: "operationAid/KeyWordUsageRecord/query",
        params:{
            categoryName: categoryName,
            type: mark,
            groupId: groupId,
        },
        success: success,
        error: err => {
            console.log(err);
        }
    })
}
/**
 * 移除关键词记录用途标记
 * @param vue {Vue} 当前页面对象 即 this
 * @param idJsonList {string} 主键列表 json 化字符串
 * @param mark {string} 标记类型 IS_APPEND_ZTC/IS_GENERATE_TITLE/IS_GENERATE_ORDER_PLAN
 * @param success {Function} 请求成功的回调方法
 * @param finallyFuc {Function} 请求最终的回调方法
 * */
export function removeKeyWordUsage(vue,idJsonList,mark,success,finallyFuc) {
    vue.$request.post({
        url: "operationAid/KeyWordUsageRecord/status",
        params:{
            ids: idJsonList,
            type: mark,
        },
        success: success,
        error: err => {
            console.log(err);
        },
        finally: finallyFuc
    })
}

/**
 * 提交功能参数模板
 * @param vue {Vue} 当前页面对象 即 this
 * @param params {Object} 请求参数对象
 * @param success {Function} 请求成功回调方法
 * */
export function commitFeatureParamTemplate(vue,params,success){
    vue.$request.post({
        url: "operationAid/featureParamTemplate/commit",
        params: {...params},
        success: success
    })
}

/**
 * 删除功能参数模板
 * */
export function removeFeatureParamTemplate(vue,jsonIds,success){
    vue.$request.post({
        url: 'operationAid/featureParamTemplate/delete',
        params: {
            jsonIds: jsonIds
        },
        success: success,
    })
}

/**
 * 获取功能参数模板
 * @param vue {Vue} 当前页面对象 即 this
 * @param type {string} 数据类型
 * @param success {Function} 请求成功回调方法
 * @param finallyFuc {Function} 请求方法最终回调方法
 * */
export function getFeatureParamTemplate(vue,type,success,finallyFuc){
    vue.$request.post({
        url: "operationAid/featureParamTemplate/table",
        params: {
            type: type,
        },
        success: success,
        finally: finallyFuc
    })
}

/**
 * 获取品牌关键字
 * @param vue {Vue} 当前页面对象 即 this
 * @param success {Function} 请求成功回调方法
 * */
export function getKeyWordBrandCharacter(vue, success){
    vue.$request.post({
        url: "operationAid/KeyWordBrandCharacter/list",
        params:{},
        success: success,
        error: err => {
            console.log(err);
        }
    })
}

/**
 * 获取品牌关键字
 * @param vue {Vue} 当前页面对象 即 this
 * @param name {string} 新增的关键字品牌的名称
 * @param success {Function} 请求成功回调方法
 * */
export function addKeyWordBrandCharacter(vue, name, success){
    vue.$request.post({
        url: "operationAid/KeyWordBrandCharacter/commit",
        params:{
            name: name
        },
        success: success,
        error: err => {
            console.log(err);
        }
    })
}

/**
 * 移除品牌关键字
 * @param id {string} 移除品牌关键字id
 * @param vue {Vue} 当前页面对象 即 this
 * @param success {Function} 请求成功回调方法
 * */
export function delKeyWordBrandCharacter(vue, id, success) {
    vue.$request.post({
        url: "operationAid/KeyWordBrandCharacter/delete",
        params:{
            ids: id
        },
        success: success,
        error: err => {
            console.log(err);
        }
    })
}

const brandWord = ["苏泊尓", "迈巴勒", "乌兹别克斯坦", "章丘", "官方", "炊大皇", "康巴赫", "树可", "卡罗特", "三禾", "wmf", "九阳", "双立", "迈巴赫", "厨之翼", "鹅妈妈", "金嫂子", "马克西姆", "美的", "温仑山", "网易严选", "奥康达", "德萨克", "吹大王", "宜家", "张小泉", "维氏", "奥克斯", "双喜", "欧莱克", "志高", "松下", "泊尔", "摩动", "神州", "黄老大", "康宁", "摩兰德", "龙泉", "王麻子", "十八子", "陈枝记", "18子", "狂鲨", "孙兴", "李培德", "葛华", "摩飞", "七彩叮当", "中康", "神田", "华邦", "宏江", "中福", "窒化", "陆川铁人牌", "旗舰", "康硕士", "维亿", "小帅锅", "吉川", "顺达", "揭宝", "厨之友", "洛德", "欧洛德", '黄小厨', '小熊', '焠大皇']

export default brandWord
